package com.jcfk.eam.service.main;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamRepairOrderDao;
import com.jcfk.eam.domain.dto.base.*;
import com.jcfk.eam.domain.dto.main.EamAssetInfoDTO;
import com.jcfk.eam.domain.dto.main.EamRepairOrderPartDTO;
import com.jcfk.eam.domain.dto.main.EamRepairOrderPersonDTO;
import com.jcfk.eam.domain.dto.main.RepairOrderSummaryDTO;
import com.jcfk.eam.domain.po.base.*;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.po.main.EamRepairOrderPart;
import com.jcfk.eam.domain.po.main.EamRepairOrderPerson;
import com.jcfk.eam.domain.po.main.EamRepairOrderTransmit;
import com.jcfk.eam.domain.po.mould.EamMouldTaskInfo;
import com.jcfk.eam.domain.query.base.EamRepairOrderQuery;
import com.jcfk.eam.enums.AssetInfoStatusEnum;
import com.jcfk.eam.enums.RepairOrderRecordOperateType;
import com.jcfk.eam.service.base.EamAssetTypeService;
import com.jcfk.eam.service.base.EamSparePartService;
import com.jcfk.eam.service.base.EamTeamMemberService;
import com.jcfk.eam.service.base.EamTeamService;
import com.jcfk.eam.service.mould.EamMouldTaskInfoService;
import com.jcfk.system.api.ifeign.SysUserServiceFeign;
import com.jcfk.system.api.utils.CodeBuildUtils;
import com.jcfk.system.domain.dto.SysUserDTO;
import com.jcfk.system.domain.query.SysUserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 维修单
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-26
 */
@Service
public class EamRepairOrderService extends BaseService<EamRepairOrderDao, EamRepairOrder> {

    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    @Autowired
    private EamRepairOrderFileService eamRepairOrderFileService;

    @Autowired
    private EamAssetTypeService eamAssetTypeService;

    @Autowired
    private EamTeamService eamTeamService;

    @Autowired
    private EamRepairOrderPartService eamRepairOrderPartService;

    @Autowired
    private EamSparePartService eamSparePartService;

    @Autowired
    private EamMouldTaskInfoService eamMouldTaskInfoService;

    @Autowired
    private EamRepairOrderTransmitService eamRepairOrderTransmitService;

    /**
     * 用户服务
     */
    @Autowired
    private SysUserServiceFeign sysUserServiceFeign;

    @Resource
    private EamRepairOrderPersonService eamRepairOrderPersonService;

    @Resource
    private EamRepairOrderService eamRepairOrderService;
    @Autowired
    private EamTeamMemberService eamTeamMemberService;
    @Autowired
    private EamWorkOrderRecordService eamWorkOrderRecordService;
    @Autowired
    private EamCheckAnomalyTrackingService eamCheckAnomalyTrackingService;

    /**
     * EamRepairOrder分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamRepairOrderDTO> queryByPage(DataPage<EamRepairOrderDTO> page, EamRepairOrderQuery query) {
        // 分页查询
        query.setFaultReason(StringUtils.isEmpty(query.getFaultReason()) ? query.getFaultReason() : query.getFaultReason() + "%");
        query.setFaultPosition(StringUtils.isEmpty(query.getFaultPosition()) ? query.getFaultPosition() : query.getFaultPosition() + "%");
        query.setRepairSituation(StringUtils.isEmpty(query.getRepairSituation()) ? query.getRepairSituation() : query.getRepairSituation() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 分页查询备件使用统计
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamRepairOrderDTO> queryUsageStatistics(DataPage<EamRepairOrderDTO> page, EamRepairOrderQuery query) {
        // 分页查询
        query.setFaultReason(StringUtils.isEmpty(query.getFaultReason()) ? query.getFaultReason() : query.getFaultReason() + "%");
        query.setFaultPosition(StringUtils.isEmpty(query.getFaultPosition()) ? query.getFaultPosition() : query.getFaultPosition() + "%");
        query.setRepairSituation(StringUtils.isEmpty(query.getRepairSituation()) ? query.getRepairSituation() : query.getRepairSituation() + "%");
        page = this.baseMapper.queryUsageStatistics(page, query);
        return page;
    }

    public RepairOrderSummaryDTO getRepairOrderSummary(EamRepairOrderQuery repairOrderQuery) {
        RepairOrderSummaryDTO repairOrderSummaryDTO = this.baseMapper.getRepairOrderSummary(repairOrderQuery);
        return repairOrderSummaryDTO;
    }

    /**
     * 分页查询我的维修单
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamRepairOrderDTO> queryMyRepairOrder(DataPage<EamRepairOrderDTO> page, EamRepairOrderQuery query) {
        // 分页查询
        query.setFaultReason(StringUtils.isEmpty(query.getFaultReason()) ? query.getFaultReason() : query.getFaultReason() + "%");
        query.setFaultPosition(StringUtils.isEmpty(query.getFaultPosition()) ? query.getFaultPosition() : query.getFaultPosition() + "%");
        query.setRepairSituation(StringUtils.isEmpty(query.getRepairSituation()) ? query.getRepairSituation() : query.getRepairSituation() + "%");
        page = this.baseMapper.queryMyRepairOrder(page, query);
        return page;
    }

    public RepairOrderSummaryDTO getMyRepairOrderSummary(EamRepairOrderQuery repairOrderQuery) {
        RepairOrderSummaryDTO repairOrderSummary = this.baseMapper.getMyRepairOrderSummary(repairOrderQuery);
        return repairOrderSummary;
    }

    /**
     * 判断EamRepairOrder是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamRepairOrderDTO dto) {
        QueryWrapper<EamRepairOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入维修单
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamRepairOrderDTO dto) {

        // 保存
        EamRepairOrder item = new EamRepairOrder();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);
        item.setRepairStatus("0");
        item.setRepairCode(CodeBuildUtils.buildCode("eam_bx", ""));

        item.setRepairTime(new Date());
        item.setRepairUser(SecurityUtils.getUserId());
        item.setRepairUserName(SecurityUtils.getUserName());
        if (StrUtil.isNotEmpty(item.getRepairTeamUserEmpNo())) {

            String userIdByEmpNo = getUserIdByEmpNo(item.getRepairTeamUserEmpNo());
            item.setRepairTeamSysUser(userIdByEmpNo);
        }
        super.save(item);

        List<EamRepairOrderFile> files = new ArrayList<>();
        for (EamRepairOrderFileDTO imgae : dto.getImages()) {
            EamRepairOrderFile eamSopStandardImg = new EamRepairOrderFile();
            eamSopStandardImg.setRepairId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setRepairFileType("1");
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            eamRepairOrderFileService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) eamRepairOrderFileService.saveBatch(files);
        eamWorkOrderRecordService.saveRepairRecord(item, RepairOrderRecordOperateType.CREATED);

        if (StrUtil.isNotEmpty(dto.getPointCheckDetailId())) {
            eamCheckAnomalyTrackingService.handle(dto.getPointCheckDetailId(), item);
        }
//
//        List<EamRepairOrderExecuteFile> executeFiles = new ArrayList<>();
//        for (EamRepairOrderFileDTO imgae : dto.getExecuteFiles()) {
//            EamRepairOrderExecuteFile eamSopStandardImg = new EamRepairOrderExecuteFile();
//            eamSopStandardImg.setRepairId(item.getId());
//            eamSopStandardImg.setUrl(imgae.getUrl());
//            eamSopStandardImg.setFileType(imgae.getFileType());
//            eamSopStandardImg.setFilename(imgae.getFilename());
//            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
//            eamSopStandardImg.setPath(imgae.getPath());
//            eamRepairOrderExecuteFileService.setDefaultValue(eamSopStandardImg);
//            executeFiles.add(eamSopStandardImg);
//        }
//
//        if (executeFiles.size() > 0) eamRepairOrderExecuteFileService.saveBatch(executeFiles);


    }

    /**
     * 更新维修单
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamRepairOrderDTO dto) {

        // 保存维修工单
        EamRepairOrder item = new EamRepairOrder();
        BeanUtils.copyProperties(dto, item);
        // 默认数据
        this.setDefaultValue(item);
        if (StrUtil.isNotEmpty(item.getRepairTeamUserEmpNo())) {
            String userIdByEmpNo = getUserIdByEmpNo(item.getRepairTeamUserEmpNo());
            item.setRepairTeamSysUser(userIdByEmpNo);
        } else {
            item.setRepairTeamSysUser("");
        }
        this.baseMapper.updateById(item);

        // 保存报修单附件
        QueryWrapper<EamRepairOrderFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamRepairOrderFile::getRepairId, dto.getId());
        queryWrapper.lambda().eq(EamRepairOrderFile::getRepairFileType, "1");
        eamRepairOrderFileService.remove(queryWrapper);
        List<EamRepairOrderFile> files = new ArrayList<>();
        for (EamRepairOrderFileDTO imgae : dto.getImages()) {
            EamRepairOrderFile eamSopStandardImg = new EamRepairOrderFile();
            eamSopStandardImg.setRepairId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setRepairFileType("1");
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            eamRepairOrderFileService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) eamRepairOrderFileService.saveBatch(files);

        //保存维修单附件
        QueryWrapper<EamRepairOrderFile> eamRepairOrderExecuteFileQueryWrapper = new QueryWrapper<>();
        eamRepairOrderExecuteFileQueryWrapper.lambda().eq(EamRepairOrderFile::getRepairId, dto.getId());
        eamRepairOrderExecuteFileQueryWrapper.lambda().eq(EamRepairOrderFile::getRepairFileType, "2");
        eamRepairOrderFileService.remove(eamRepairOrderExecuteFileQueryWrapper);

        List<EamRepairOrderFile> executeFiles = new ArrayList<>();
        for (EamRepairOrderFileDTO image : dto.getExecuteFiles()) {
            EamRepairOrderFile eamSopStandardImg = new EamRepairOrderFile();
            eamSopStandardImg.setRepairId(item.getId());
            eamSopStandardImg.setUrl(image.getUrl());
            eamSopStandardImg.setFileType(image.getFileType());
            eamSopStandardImg.setFilename(image.getFilename());
            eamSopStandardImg.setRepairFileType("2");
            eamSopStandardImg.setOriginalfilename(image.getOriginalfilename());
            eamSopStandardImg.setPath(image.getPath());
            eamRepairOrderFileService.setDefaultValue(eamSopStandardImg);
            executeFiles.add(eamSopStandardImg);
        }
        if (executeFiles.size() > 0) eamRepairOrderFileService.saveBatch(executeFiles);

        //保存使用备件
        QueryWrapper<EamRepairOrderPart> partQueryWrapper = new QueryWrapper<>();
        partQueryWrapper.lambda().eq(EamRepairOrderPart::getRepairId, dto.getId());
        eamRepairOrderPartService.remove(partQueryWrapper);
        List<EamRepairOrderPart> partList = new ArrayList<>();
        for (EamRepairOrderPartDTO partDTO : dto.getParts()) {
            EamRepairOrderPart orderPart = new EamRepairOrderPart();
            orderPart.setRepairId(item.getId());
            orderPart.setSparePartId(partDTO.getSparePartId());
            orderPart.setSparePartNumber(partDTO.getSparePartNumber());
            eamRepairOrderPartService.setDefaultValue(orderPart);
            partList.add(orderPart);
        }
        if (partList.size() > 0) {
            eamRepairOrderPartService.saveBatch(partList);
        }
        List<String> notExistUsers = new ArrayList<>();
        eamRepairOrderPersonService.remove(Wrappers.<EamRepairOrderPerson>lambdaQuery().eq(EamRepairOrderPerson::getOrderId, item.getId()));
        if (CollUtil.isNotEmpty(dto.getRepairOrderPersons())) {
            List<EamRepairOrderPerson> repairOrderPersonList = dto.getRepairOrderPersons().stream().map(person -> {
                EamRepairOrderPerson eamInspectionPlanPerson = new EamRepairOrderPerson();
                BeanUtils.copyProperties(person, eamInspectionPlanPerson);
                eamRepairOrderPersonService.setDefaultValue(eamInspectionPlanPerson);
                eamInspectionPlanPerson.setOrderId(item.getId());
                try {
                    String userIdByEmpNo = getUserIdByEmpNo(person.getPersonEmpNo());
                    eamInspectionPlanPerson.setUserId(userIdByEmpNo);
                } catch (RuntimeException e) {
                    notExistUsers.add(person.getPersonName());
                }
                return eamInspectionPlanPerson;
            }).collect(Collectors.toList());
            Assert.isTrue(CollUtil.isEmpty(notExistUsers), "未查询到:" + StrUtil.join(",", notExistUsers) + "人员信息");
            eamRepairOrderPersonService.saveBatch(repairOrderPersonList);
        }
    }

    /**
     * 根据批量主键删除维修单(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamRepairOrderDTO dto) {

        EamRepairOrder item = new EamRepairOrder();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamRepairOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamRepairOrder item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取维修单信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamRepairOrderDTO get(String id) {
        // 查询数据
        EamRepairOrder item = this.baseMapper.selectById(id);
        EamRepairOrderDTO dto = new EamRepairOrderDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        if (dto.getRepairTeamId() != null && !dto.getRepairTeamId().equals(""))
            dto.setRepairTeamCode(eamTeamService.get(item.getRepairTeamId()).getTeamCode());

        EamAssetInfoDTO eamAssetInfoDTO = eamAssetInfoService.get(item.getAssetId());
        if (eamAssetInfoDTO != null) {
            dto.setAssetName(eamAssetInfoDTO.getAssetName());
            dto.setAssetCode(eamAssetInfoDTO.getAssetCode());
            dto.setUsingDepartmentId(eamAssetInfoDTO.getUsingDepartmentId());
            dto.setUsingDepartmentName(eamAssetInfoDTO.getUsingDepartmentName());
            dto.setLocationName(eamAssetInfoDTO.getLocationName());
            dto.setUsingPersonName(eamAssetInfoDTO.getAssetBrandName());
            dto.setAssetBrandName(eamAssetInfoDTO.getAssetBrandName());
            dto.setAssetModelNo(eamAssetInfoDTO.getAssetModelNo());

            EamAssetTypeDTO eamAssetTypeDTO = eamAssetTypeService.get(eamAssetInfoDTO.getAssetTypeId());
            if (eamAssetTypeDTO != null) {
                dto.setAssetTypeId(eamAssetTypeDTO.getId());
                dto.setAssetTypeCode(eamAssetTypeDTO.getAssetTypeCode());
                dto.setAssetTypeName(eamAssetTypeDTO.getAssetTypeName());
            }
        }

        QueryWrapper<EamRepairOrderFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamRepairOrderFile::getRepairId, dto.getId());
        queryWrapper.lambda().eq(EamRepairOrderFile::getRepairFileType, "1");
        List<EamRepairOrderFile> list = eamRepairOrderFileService.list(queryWrapper);
        dto.setImages(convertList(list, EamRepairOrderFileDTO.class));

        //查询使用备件情况
        QueryWrapper<EamRepairOrderPart> partQw = new QueryWrapper<>();
        partQw.lambda().eq(EamRepairOrderPart::getRepairId, id);
        List<EamRepairOrderPart> parts = eamRepairOrderPartService.list(partQw);

        List<String> ids = parts.stream().map(EamRepairOrderPart::getSparePartId).collect(Collectors.toList());

        List<EamRepairOrderPartDTO> details = convertList(parts, EamRepairOrderPartDTO.class);
        dto.setParts(new ArrayList<>());
        if (ids.size() > 0) {
            QueryWrapper<EamSparePart> partQueryWrapper = new QueryWrapper<>();
            partQueryWrapper.in("id", ids);
            List<EamSparePart> eamSpareParts = eamSparePartService.list(partQueryWrapper);
            Map<String, EamSparePart> map = new HashMap<>();
            for (EamSparePart eamSparePart : eamSpareParts) {
                map.put(eamSparePart.getId(), eamSparePart);
            }

            for (EamRepairOrderPartDTO partDTO : details) {
                EamSparePart eamSparePart = map.get(partDTO.getSparePartId());
                if (eamSparePart != null) {
                    partDTO.setSpareCode(eamSparePart.getSpareCode());
                    partDTO.setSpareName(eamSparePart.getSpareNmae());
                    partDTO.setSpareType(eamSparePart.getSpareType());
                    partDTO.setSpareUnit(eamSparePart.getSpareUnit());
                    dto.getParts().add(partDTO);
                }
            }
        }

        QueryWrapper<EamRepairOrderFile> eamRepairOrderExecuteFileQueryWrapper = new QueryWrapper<>();
        eamRepairOrderExecuteFileQueryWrapper.lambda().eq(EamRepairOrderFile::getRepairId, dto.getId());
        eamRepairOrderExecuteFileQueryWrapper.lambda().eq(EamRepairOrderFile::getRepairFileType, "2");
        List<EamRepairOrderFile> eamRepairOrderExecuteFiles = eamRepairOrderFileService.list(eamRepairOrderExecuteFileQueryWrapper);
        dto.setExecuteFiles(convertList(eamRepairOrderExecuteFiles, EamRepairOrderFileDTO.class));

        // 获取实际参与人
        List<EamRepairOrderPerson> eamRepairOrderPeopleList = eamRepairOrderPersonService.list(Wrappers.<EamRepairOrderPerson>lambdaQuery()
                .eq(EamRepairOrderPerson::getOrderId, item.getId()));
        List<String> userIds = eamRepairOrderPeopleList.stream().map(EamRepairOrderPerson::getUserId).collect(Collectors.toList());
        RetResult<?> result = sysUserServiceFeign.getList(new SysUserQuery());
        Map<String, Map<String, String>> sysUserDTOMap = new HashMap<>();
        if (result != null) {
            List<Map<String, String>> data = (List<Map<String, String>>) result.getData();
            if (data != null) {
                sysUserDTOMap = data.stream().filter(x -> userIds.contains(x.get("id"))).collect(Collectors.toMap(t -> t.get("id"), Function.identity()));
            }
        }
        Map<String, Map<String, String>> finalSysUserDTOMap = sysUserDTOMap;
        dto.setRepairOrderPersons(eamRepairOrderPeopleList.stream().map(x -> {
            EamRepairOrderPersonDTO orderPersonDTO = new EamRepairOrderPersonDTO();
            BeanUtils.copyProperties(x, orderPersonDTO);
            orderPersonDTO.setPersonEmpNo(finalSysUserDTOMap.get(x.getUserId()).get("empNo"));
            return orderPersonDTO;
        }).collect(Collectors.toList()));
        return dto;
    }

    /**
     * 更新维修单状态
     *
     * @param eamRepairOrderDTO
     */
    public void updateStatus(EamRepairOrderStatusDTO eamRepairOrderDTO) {
        EamRepairOrder repairOrder = this.getById(eamRepairOrderDTO.getId());
        String extra = null;
        if (repairOrder != null) {
            // 应答
            if (eamRepairOrderDTO.getRepairStatus().equals("1")) {
                // 应答人id
                String userId = SecurityUtils.getUserId();
                RetResult<SysUserDTO> sysUserDTORetResult = sysUserServiceFeign.get(userId);
                Assert.isTrue(sysUserDTORetResult != null && sysUserDTORetResult.getData() != null, "用户不存在");
                repairOrder.setRepairTeamSysUser(userId);
                // 根据用户工号获取维修组成员信息
                EamTeamMember eamTeamMember = eamTeamMemberService.getOne(Wrappers.<EamTeamMember>lambdaQuery()
                        .eq(EamTeamMember::getMemberEmpNo, sysUserDTORetResult.getData().getEmpNo())
                        .last("limit 1"));
                Assert.isTrue(eamTeamMember != null, "当前应答用户不是维修组成员");
                repairOrder.setAnswerTime(new Date());
                repairOrder.setRepairTeamUser(eamTeamMember.getId());
                repairOrder.setRepairTeamUserName(eamTeamMember.getMemberName());
                repairOrder.setRepairTeamUserEmpNo(eamTeamMember.getMemberEmpNo());
                // 获取维修组信息
                EamTeam eamTeam = eamTeamService.getOne(Wrappers.<EamTeam>lambdaQuery()
                        .eq(EamTeam::getId, eamTeamMember.getTeamId())
                        .last("limit 1"));
                repairOrder.setRepairTeamId(eamTeam.getId());
                repairOrder.setRepairTeamName(eamTeam.getTeamName());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
            }

            // 开始维修
            if (eamRepairOrderDTO.getRepairStatus().equals("2")) {
                repairOrder.setRepairStartTime(new Date());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
            }

            // 维修完成
            if (eamRepairOrderDTO.getRepairStatus().equals("3")) {
                repairOrder.setRepairEndTime(new Date());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
                //维修完成更新台账状态
                updateMould(repairOrder.getAssetId(), AssetInfoStatusEnum.NORMAL);
                //出库任务发起维修单，在维修完成后把维修单状态从维修中变成正常
                if (StrUtil.isNotEmpty(repairOrder.getTaskId())) {
                    updateTask(repairOrder.getTaskId());
                }
            }

            // 待确认
            if (eamRepairOrderDTO.getRepairStatus().equals("4")) {
                repairOrder.setRepairEndTime(new Date());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
//                eamCheckAnomalyTrackingService.finished(repairOrder.getId(), eamRepairOrderDTO.getRepairStatus(), eamRepairOrderDTO.getMemo());
            }

            // 确认完成/关闭
            if (eamRepairOrderDTO.getRepairStatus().equals("5") || eamRepairOrderDTO.getRepairStatus().equals("7")) {
                repairOrder.setFinishTime(new Date());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
                repairOrder.setMemo(eamRepairOrderDTO.getMemo());
                extra = eamRepairOrderDTO.getMemo();
//                eamCheckAnomalyTrackingService.finished(repairOrder.getId(), eamRepairOrderDTO.getRepairStatus(), eamRepairOrderDTO.getMemo());
            }
            //取消
            if (eamRepairOrderDTO.getRepairStatus().equals("6")) {
                repairOrder.setFinishTime(new Date());
                repairOrder.setRepairStatus(eamRepairOrderDTO.getRepairStatus());
                repairOrder.setMemo(eamRepairOrderDTO.getMemo());
                extra = eamRepairOrderDTO.getMemo();
                updateMould(repairOrder.getAssetId(), AssetInfoStatusEnum.NORMAL);
                if (StrUtil.isNotEmpty(repairOrder.getTaskId())) {
                    updateTask(repairOrder.getTaskId());
                }
                //                eamCheckAnomalyTrackingService.finished(repairOrder.getId(), eamRepairOrderDTO.getRepairStatus(), eamRepairOrderDTO.getMemo());

            }
            this.setDefaultValue(repairOrder);
            this.updateById(repairOrder);
            RepairOrderRecordOperateType operateType = RepairOrderRecordOperateType.getByValue(eamRepairOrderDTO.getRepairStatus());
            eamWorkOrderRecordService.saveRepairRecord(repairOrder, operateType, extra);
        }
    }

    /**
     * 更新台账状态
     *
     * @param id
     * @param statusEnum
     */
    public void updateMould(String id, AssetInfoStatusEnum statusEnum) {
        QueryWrapper<EamAssetInfo> eamAssetInfoQueryWrapper = new QueryWrapper<>();
        eamAssetInfoQueryWrapper.lambda().eq(EamAssetInfo::getId, id);
        EamAssetInfo eamAssetInfo = new EamAssetInfo();
        eamAssetInfo.setAssetStatus(statusEnum.getCode());
        eamAssetInfoService.update(eamAssetInfo, eamAssetInfoQueryWrapper);
    }

    /**
     * 更新任务状态成正常
     *
     * @param taskId
     */
    public void updateTask(String taskId) {
        EamMouldTaskInfo eamMouldTaskInfo = new EamMouldTaskInfo();
        eamMouldTaskInfo.setId(taskId);
        eamMouldTaskInfo.setTaskStatus(0);
        eamMouldTaskInfo.setLastUpdatedUserId(SecurityUtils.getUserId());
        eamMouldTaskInfo.setLastUpdateTime(new Date());
        eamMouldTaskInfo.setLastUpdatedUserName(SecurityUtils.getUserName());
        eamMouldTaskInfoService.updateById(eamMouldTaskInfo);
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamRepairOrderDTO>
     */
    public List<EamRepairOrderDTO> getList(EamRepairOrderQuery query) {
        // 查询条件
        QueryWrapper<EamRepairOrder> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetId()), EamRepairOrder::getAssetId, query.getAssetId());
        qw.lambda().ge(!StrUtil.isEmpty(query.getRepairTimeStart()), EamRepairOrder::getRepairTime, query.getRepairTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getRepairTimeEnd()), EamRepairOrder::getRepairTime, query.getRepairTimeEnd());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getRepairUser()), EamRepairOrder::getRepairUser, query.getRepairUser());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getFaultReason()), EamRepairOrder::getFaultReason, query.getFaultReason());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getFaultPosition()), EamRepairOrder::getFaultPosition, query.getFaultPosition());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getRepairSituation()), EamRepairOrder::getRepairSituation, query.getRepairSituation());
        qw.lambda().eq(query.getAssetKind() != null, EamRepairOrder::getAssetKind, query.getAssetKind());
        // 查询数据
        List<EamRepairOrder> list = super.list(qw);

        return convertList(list, EamRepairOrderDTO.class);
    }

    /**
     * 根据主键获取维修单信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamRepairOrder item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    /**
     * 根据员工号获取用户主键
     *
     * @param empNo
     * @return
     */
    public String getUserIdByEmpNo(String empNo) {
        List<String> empNoList = new ArrayList<>();
        empNoList.add(empNo);
        RetResult<List<String>> userIdList = sysUserServiceFeign.getUseridsForUserNo(empNoList);

        if (userIdList.getData() != null && userIdList.getData().size() > 0) {
            return userIdList.getData().get(0);
        } else {
            throw new RuntimeException("未获取用户主键");
        }
    }

    @Transactional
    public void transmit(EamRepairOrderTransmitDTO eamRepairOrderTransmitDTO) {
        EamRepairOrder repairOrder = this.getById(eamRepairOrderTransmitDTO.getId());
        EamRepairOrder clone = ObjectUtil.clone(repairOrder);

        String repairTeamUserId = this.getUserIdByEmpNo(eamRepairOrderTransmitDTO.getRepairTeamUserEmpNo());
        eamRepairOrderTransmitDTO.setRepairTeamUser(repairTeamUserId);

        if (repairOrder != null) {
            // 设置工单维修人
            repairOrder.setRepairTeamId(eamRepairOrderTransmitDTO.getRepairTeamId());
            repairOrder.setRepairTeamName(eamRepairOrderTransmitDTO.getRepairTeamName());
            repairOrder.setRepairTeamUser(eamRepairOrderTransmitDTO.getRepairTeamUser());
            repairOrder.setRepairTeamUserName(eamRepairOrderTransmitDTO.getRepairTeamUserName());
            repairOrder.setRepairTeamUserEmpNo(eamRepairOrderTransmitDTO.getRepairTeamUserEmpNo());
            repairOrder.setRepairStatus("1");
            this.setDefaultValue(repairOrder);
            this.updateById(repairOrder);

            //记录转交记录
            EamRepairOrderTransmit eamRepairOrderTransmit = new EamRepairOrderTransmit();
            eamRepairOrderTransmit.setRepairId(repairOrder.getId());
            eamRepairOrderTransmit.setFromRepairTeamId(clone.getRepairTeamId());
            eamRepairOrderTransmit.setFromRepairTeamName(clone.getRepairTeamName());
            eamRepairOrderTransmit.setFromRepairTeamUser(clone.getRepairTeamUser());
            eamRepairOrderTransmit.setFromRepairTeamUserName(clone.getRepairTeamUserName());
            eamRepairOrderTransmit.setFromRepairTeamUserEmpNo(clone.getRepairTeamUserEmpNo());
            eamRepairOrderTransmit.setToRepairTeamId(repairOrder.getRepairTeamId());
            eamRepairOrderTransmit.setToRepairTeamName(repairOrder.getRepairTeamName());
            eamRepairOrderTransmit.setToRepairTeamUser(repairOrder.getRepairTeamUser());
            eamRepairOrderTransmit.setToRepairTeamUserName(repairOrder.getRepairTeamUserName());
            eamRepairOrderTransmit.setToRepairTeamUserEmpNo(repairOrder.getRepairTeamUserEmpNo());
            eamRepairOrderTransmit.setRemarks(repairOrder.getRemarks());

            eamRepairOrderTransmitService.save(eamRepairOrderTransmit);
            eamWorkOrderRecordService.saveRepairRecord(repairOrder,
                    RepairOrderRecordOperateType.TRANSFER,
                    (StrUtil.isNotEmpty(eamRepairOrderTransmit.getFromRepairTeamUserName()) ? ("由" + eamRepairOrderTransmit.getFromRepairTeamUserName()) : "")
                            + "转交给" + eamRepairOrderTransmit.getToRepairTeamUserName());
        }
    }

    @Transactional
    public void outSourcingStart(EamRepairOrderStatusDTO eamRepairOrderDTO) {
        EamRepairOrder repairOrder = this.getById(eamRepairOrderDTO.getId());
        if (repairOrder != null) {
            repairOrder.setOutSourcing("1");
            repairOrder.setOutSourcingStartTime(new Date());
            this.setDefaultValue(repairOrder);
            this.updateById(repairOrder);
            eamWorkOrderRecordService.saveRepairRecord(repairOrder, RepairOrderRecordOperateType.OUT_SOURCING_START);
        }
    }

    @Transactional
    public void outSourcingFinish(EamRepairOrderStatusDTO eamRepairOrderDTO) {
        EamRepairOrder repairOrder = this.getById(eamRepairOrderDTO.getId());
        if (repairOrder != null) {
            this.setDefaultValue(repairOrder);
            this.updateById(repairOrder);
            eamWorkOrderRecordService.saveRepairRecord(repairOrder, RepairOrderRecordOperateType.OUT_SOURCING_FINISH);
        }
    }

    @Transactional
    public void assign(EamRepairOrderStatusDTO eamRepairOrderDTO) {
        EamRepairOrder repairOrder = this.getById(eamRepairOrderDTO.getId());
        if (repairOrder != null) {
            repairOrder.setOutSourcing("2");
            repairOrder.setOutSourcingEndTime(new Date());
            repairOrder.setRepairTeamId(eamRepairOrderDTO.getRepairTeamId());
            repairOrder.setRepairTeamName(eamRepairOrderDTO.getRepairTeamName());
            repairOrder.setRepairStatus("1");
            String repairTeamUserId = this.getUserIdByEmpNo(eamRepairOrderDTO.getRepairTeamUserEmpNo());
            repairOrder.setRepairTeamUser(repairTeamUserId);
            repairOrder.setRepairTeamUserName(eamRepairOrderDTO.getRepairTeamUserName());
            repairOrder.setRepairTeamUserEmpNo(eamRepairOrderDTO.getRepairTeamUserEmpNo());
            this.setDefaultValue(repairOrder);
            this.updateById(repairOrder);
            eamWorkOrderRecordService.saveRepairRecord(repairOrder, RepairOrderRecordOperateType.ASSIGN, StrUtil.format("指派给{}", eamRepairOrderDTO.getRepairTeamUserName()));
        }
    }
}

